package online.szlib.com.rest.controller;

import net.sf.json.JSONObject;
import online.szlib.com.common.utils.JOSEHelper;
import online.szlib.com.common.utils.JSONHelper;
import online.szlib.com.core.domain.User;
import online.szlib.com.core.services.UserService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class LogInOutRestController {

    private static Logger logger = LoggerFactory.getLogger(LogInOutRestController.class);

    @Autowired
    private UserService userService;
   
	@Autowired
	private JOSEHelper joseHelper;
    
	// Http Post Login
	@RequestMapping(value="/api/login", method = RequestMethod.POST)
	public ResponseEntity<JSONObject> login(@RequestBody User user) throws Exception {
		logger.debug("login and get one user >>>>>>>>>>>>>>>>>>>>");
		User loginUser = userService.login(user.getUserName(), user.getPassword());
		JSONObject json2 = new JSONObject();
		
		boolean login = (loginUser != null);
		json2.put("success", login ? "1" : "0");
		
		if (loginUser != null) {
			json2.put("uid", loginUser.getUserId());
			json2.put("jwt", joseHelper.getEncryptJWEObject(loginUser.getUserName()).serialize());
		}
		
		return new ResponseEntity<JSONObject>(json2, JSONHelper.getJSONHeaders(), HttpStatus.OK);
	}
}
